
// 控制的是播放的业务逻辑, 具体的播放, 暂停功能实现

import UIKit
import AVFoundation
import FreeStreamer

class MusicOperationTool: NSObject {

    var currentModel = musicModel(dict:[:])
    static let shareInstance = MusicOperationTool()
    
    let tool = singleMusicTool()
        
    // 播放的音乐列表
    var musicMs:Array<musicModel> = [musicModel]()

    var currentPlayIndex = 0 {
        didSet {
            if currentPlayIndex < 0
            {
                currentPlayIndex = (musicMs.count) - 1
            }
            if currentPlayIndex > (musicMs.count) - 1
            {
                currentPlayIndex = 0
            }
        }
    }
    
    fileprivate var musicMessageModel = MusicMessageModel()
    
    func getMusicMessageModel() -> MusicMessageModel {
        
        // 在这里, 保持, 数据的最新状态, 就可以
        // 当前正在播放的歌曲信息
        musicMessageModel.musicM = musicMs[currentPlayIndex]
        
        let currentTime = tool.audioStream.currentTimePlayed.second+tool.audioStream.currentTimePlayed.minute*60
        let totalTime = tool.audioStream.duration.second+tool.audioStream.duration.minute*60
        
        musicMessageModel.costTime = currentTime 
        musicMessageModel.totalTime = totalTime 
        
        musicMessageModel.isPlaying = tool.player?.status == .readyToPlay ? false:true
        
        return musicMessageModel
    }
    
    func playMusic(_ musicM: musicModel) -> () {
        // 播放数据模型对应的音乐
        tool.initAudioStream(musicM)
        currentPlayIndex = musicMs.index(of: musicM)!
        currentModel = musicM
        CLNotificationCenter.post(name: Notification.Name(rawValue: "musicPlay"), object:musicM)
    }
    
    func playCurrentMusic() -> () {
        // 取出需要播放的音乐数据模型
        let model = musicMs[currentPlayIndex]
        // 播放音乐模型
        playMusic(model)
    }
    
    func pauseCurrentMusic() -> () {
        // 根据音乐模型, 进行暂停
        tool.audioStream.pause()
    }
    
    
    func nextMusic() -> () {
        tool.audioStream.pause()

        currentPlayIndex += 1
        print(currentPlayIndex)
        // 取出需要播放的音乐数据模型
        let model = musicMs[currentPlayIndex]
        // 根据音乐模型, 进行播放
        playMusic(model)
        
    }
    func preMusic() -> () {
        currentPlayIndex -= 1
        // 取出需要播放的音乐数据模型
        let model = musicMs[currentPlayIndex]
        
        // 根据音乐模型, 进行播放
        playMusic(model)
    }
    
    // 停止转动
    func stopIconRotion(_ imageV:UIImageView){
        imageV.layer.removeAllAnimations()
    }
    // 开始转动
    func iconRotation(_ imageV:UIImageView,duration:TimeInterval){
        
        let rotation = CABasicAnimation()
        rotation.duration = duration
        rotation.isRemovedOnCompletion = false
        rotation.repeatCount = MAXFLOAT
        rotation.keyPath = "transform.rotation.z"
        rotation.toValue = (M_PI*2)
        rotation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
        imageV.layer.add(rotation, forKey: nil)
    }
}
